package com.wx.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.wx.rabbitmq.entity.Order;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @ClassName RabbitConsumers
 * @Author wx
 * @Description 消费者
 * @Date 2018-11-25-22:42
 */
@Component
public class RabbitConsumers {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${rabbitmq.test.queue.name}",
                    durable="${rabbitmq.test.queue.durable}"),
            exchange = @Exchange(value = "${rabbitmq.test.exchange.name}",
                    durable="${rabbitmq.test.exchange.durable}",
                    type= "${rabbitmq.test.exchange.type}",
                    ignoreDeclarationExceptions = "${rabbitmq.test.exchange.ignoreDeclarationExceptions}"),
            key = "${rabbitmq.test.routingkey}"
    )
    )
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception {
        System.err.println("--------------------------------------");
        System.err.println("消费端Payload: " + message.getPayload());
        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        //手工ACK
        channel.basicAck(deliveryTag, false);
    }



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${rabbitmq.order.queue.name}",
                    durable="${rabbitmq.order.queue.durable}"),
            exchange = @Exchange(value = "${rabbitmq.order.exchange.name}",
                    durable="${rabbitmq.order.exchange.durable}",
                    type= "${rabbitmq.order.exchange.type}",
                    ignoreDeclarationExceptions = "${rabbitmq.order.exchange.ignoreDeclarationExceptions}"),
            key = "${rabbitmq.order.routingkey}"
    )
    )
    @RabbitHandler
    public void onOrderMessage(@Payload Order order,
                               Channel channel,
                               @Headers Map<String, Object> headers) throws Exception {
        System.err.println("--------------------------------------");
        System.err.println("消费端order: " + order.getId());
        Long deliveryTag = (Long)headers.get(AmqpHeaders.DELIVERY_TAG);
        //手工ACK
        channel.basicAck(deliveryTag, false);
    }

}
